import { useEffect, useRef, useState } from 'react';
import { useRequest } from 'ahooks';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Modal, Space } from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import ShowIconsCollapse from './ShowIconsCollapse';
import { postMessage, MessageType } from '@inbiz/utils';
import UploadCustomIcon, { IUploadContent } from './UploadCustomIcon';
import {
  addGrop,
  allGroups,
  CustomIconType,
  deleteGrop,
  IconGroupType,
  uploadIcon,
} from '../service';
import '../index.less';

export type IProps = {
  selected: string;
  serchValue: string;
  handlePicker: (value: string, flag?: boolean) => void;
  checkSelectGroup: IconGroupType;
  setCheckSelectGroup: (group: IconGroupType) => void;
  setNowSerchValue: (str: string) => void;
  setSerchValue: (str: string) => void;
  isHideTitle?:boolean;
};

const { confirm } = Modal;
const CustomIcon = (props: IProps) => {
  const {
    selected,
    serchValue,
    handlePicker,
    checkSelectGroup,
    setCheckSelectGroup,
    setNowSerchValue,
    setSerchValue,
    isHideTitle
  } = props;
  // 数据
  const [groupData, setGroupData] = useState<IconGroupType[]>([]);
  const [showIcon, setShowIcon] = useState<CustomIconType[]>([]);
  const [form] = Form.useForm();
  const uploadContent = useRef<IUploadContent>(null);

  // 分组
  const [showAddGroup, setShowAddGroup] = useState<boolean>(false);
  const [groupName, setGroupName] = useState<string>();
  const [alreadyActiveKeys, setAlreadyActiveKeys] = useState<string[]>([]);
  const [isGroupLoading, setIsGroupLoading] = useState<boolean>(true);

  // 上传
  const [showUploadIcon, setShowUploadIcon] = useState<boolean>(false);

  const allGroupsApi = useRequest(allGroups, {
    manual: true,
  });
  const addGropApi = useRequest(addGrop, {
    manual: true,
  });
  const deleteGropApi = useRequest(deleteGrop, {
    manual: true,
  });
  const uploadIconApi = useRequest(uploadIcon, {
    manual: true,
  });
  const [btnLoading, setBtnLoading] = useState<boolean>(false);

  // 获取分组数据
  useEffect(() => {
    if (allGroupsApi.data) {
      const nowData: any = allGroupsApi.data;
      setGroupData(nowData);
      setIsGroupLoading(false);
    }
    if (allGroupsApi.loading) {
      console.log(getMessage('IconPicker.getGroupLoading'));
    }
    if (allGroupsApi.error) {
      console.log(getMessage('IconPicker.getGroupError'));
    }
  }, [allGroupsApi.data, allGroupsApi.loading, allGroupsApi.error]);

  useEffect(() => {
    if (!serchValue || serchValue.length === 0) {
      allGroupsApi.runAsync();
    }
  }, [serchValue]);

  // 新建分组
  const addGroupHandelOk = () => {
    form
      .validateFields()
      .then((values) => {
        setBtnLoading(true);
        if (values.groupName?.trim()?.length === 0) {
          message.warning(getMessage('IconPicker.groupNameNotEmptyString'));
          setBtnLoading(false);
        } else {
          const param = { name: values.groupName?.trim() };
          addGropApi
            .runAsync(param)
            .then((data) => {
              setShowAddGroup(false);
              setBtnLoading(false);
              if (!data) {
                return;
              }
              message.success(getMessage('IconPicker.addSuccess'));
              if (serchValue && serchValue?.length > 0) {
                setNowSerchValue('');
                setSerchValue('');
              } else {
                allGroupsApi.runAsync().then((data: any) => {
                  setGroupData(data);
                });
              }
            })
            .catch((error) => {
              setBtnLoading(false);
            });
          setGroupName('');
        }
      })
      .catch((err) => {
        setBtnLoading(false);
        console.log(err);
      });
  };
  const addGroupHandelCancel = () => {
    setShowAddGroup(false);
    setGroupName('');
  };

  // 上传图片
  const uploadIconHandelCancel = () => {
    setShowUploadIcon(false);
  };
  const uploadIconHandelOk = async () => {
    const form = uploadContent.current?.getForm();
    // @ts-ignore
    form
      .validateFields()
      .then((values) => {
        setBtnLoading(true);
        if (values.name?.trim()?.length === 0) {
          // message.warning('图标名称不能为空格字符串！');
          message.warning(getMessage('IconPicker.iconNameNotEmptyString'));
          setBtnLoading(false);
        } else {
        let file=values?.iconFile?.file?.originFileObj;
          uploadIconApi
            .runAsync(file?{
              ...values,
              iconFile: {file}
            }:{...values})
            .then((data: any) => {
              if (data) {
                // message通讯
                let messageData: MessageType = {
                  module: 'staticResource',
                  event: 'add',
                  data: {
                    filePath: data.Path
                  },
                };
                postMessage(messageData);
                // 如果该分组已展开，就前端加入到渲染icon中
                message.success(getMessage('IconPicker.addSuccess'));
                setShowUploadIcon(false);
                setBtnLoading(false);
                if (serchValue && serchValue?.length > 0) {
                  setNowSerchValue('');
                  setSerchValue('');
                } else {
                  if (alreadyActiveKeys?.indexOf(data.IconGroupOutId) !== -1) {
                    setShowIcon([...showIcon, data]);
                  }
                }
              } else {
                setBtnLoading(false);
              }
            })
            .catch((error) => {
              setBtnLoading(false);
            });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  function showGroupDeleteConfirm() {
    confirm({
      title: getMessage('IconPicker.deleteGroup'),
      icon: <ExclamationCircleOutlined />,
      content: getMessage('IconPicker.sureDelete') + checkSelectGroup.Name + '?',
      okText: getMessage('IconPicker.okText'),
      centered: true,
      cancelText: getMessage('IconPicker.cancelText'),
      onOk() {
        if (checkSelectGroup.IsDefault) {
          message.warning(getMessage('IconPicker.defaultGroupNotDelete'));
          return;
        }
        deleteGropApi.runAsync({ Id: checkSelectGroup.Id }).then((data) => {
          allGroupsApi.runAsync().then((data: any) => {
            setGroupData(data);
            message.success(getMessage('IconPicker.deleted'));
            setCheckSelectGroup({
              Id: '',
              OutId: '',
              AppId: '',
              IsDefault: false,
              Name: '',
            });
          });
        });
      },
    });
  }
  return (
    <div className="customIcon">
      <div className="operationButton">
        <Space size={10}>
          <Button
            type="primary"
            onClick={() => {
              setShowUploadIcon(true);
            }}
          >
            <TextWidget>IconPicker.upload</TextWidget>
          </Button>
          <Button
            type="primary"
            ghost
            onClick={() => {
              setShowAddGroup(true);
            }}
          >
            <TextWidget>IconPicker.addGroup</TextWidget>
          </Button>
          <Button
            danger
            style={{ display: checkSelectGroup.Id?.length > 0 ? 'block' : 'none' }}
            onClick={showGroupDeleteConfirm}
          >
            <TextWidget>IconPicker.deleteGroup</TextWidget>
          </Button>
        </Space>
      </div>
      <div className="collapseContent">
        <ShowIconsCollapse
          groupData={groupData}
          selected={selected}
          handlePicker={handlePicker}
          setGroupData={setGroupData}
          showIcon={showIcon}
          setShowIcon={setShowIcon}
          setIsGroupLoading={setIsGroupLoading}
          isGroupLoading={isGroupLoading}
          alreadyActiveKeys={alreadyActiveKeys}
          setAlreadyActiveKeys={setAlreadyActiveKeys}
          serchValue={serchValue}
          setCheckSelectGroup={setCheckSelectGroup}
          checkSelectGroup={checkSelectGroup}
          isHideTitle={isHideTitle}
        />
      </div>
      <Modal
        title={getMessage('IconPicker.addGroup')}
        className="addGroup"
        centered
        width={450}
        destroyOnClose
        okText={getMessage('IconPicker.okText')}
        cancelText={getMessage('IconPicker.cancelText')}
        confirmLoading={btnLoading}
        visible={showAddGroup}
        onOk={addGroupHandelOk}
        onCancel={addGroupHandelCancel}
      >
        <div className="container">
          <Form name="basic1" form={form} preserve={false}>
            <label>
              <TextWidget>IconPicker.groupName</TextWidget>
            </label>
            <Form.Item
              name="groupName"
              // label='分组名称'
              colon={false}
              rules={[{ required: true, message: getMessage('IconPicker.pleaseEnterName') }]}
            >
              <Input
                placeholder={getMessage('IconPicker.pleaseEnterName')}
                autoComplete="off"
                style={{ width: 299, height: 38 }}
                value={groupName}
                onChange={(e) => {
                  setGroupName(e.target.value);
                }}
              />
            </Form.Item>
          </Form>
        </div>
      </Modal>
      <Modal
        className="uploadIcon"
        title={getMessage('IconPicker.uploadIcon')}
        centered
        destroyOnClose
        okText={getMessage('IconPicker.okText')}
        cancelText={getMessage('IconPicker.cancelText')}
        confirmLoading={btnLoading}
        width={600}
        visible={showUploadIcon}
        onOk={uploadIconHandelOk}
        onCancel={uploadIconHandelCancel}
      >
        <UploadCustomIcon
          groupData={groupData}
          ref={uploadContent}
          checkSelectGroup={checkSelectGroup}
        />
      </Modal>
    </div>
  );
};

export default CustomIcon;
